package cn.edu.swpu.sims.controller;

import cn.edu.swpu.sims.model.Student;
import cn.edu.swpu.sims.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * @author 码之泪殇
 * @date 2020/9/12 14:53
 * 到达胜利之前，无法回头
 */
@Controller
@RequestMapping("/student")
@Slf4j
public class StudentController {

    @Autowired
    private StudentService studentService;

    @GetMapping("/show")
    public ModelAndView studentList(@RequestParam(value = "searchType", defaultValue = "sno") String searchType, String s_Text) {
        ModelAndView mv = new ModelAndView("mainAdmin");
        log.info(s_Text);
        List<Student> studentList = studentService.getAllStudent(searchType,s_Text);
        mv.addObject("studentList",studentList);
        mv.addObject("mainPage","admin/studentList.jsp");
        return mv;
    }

    @GetMapping("/add")
    public ModelAndView addStudentPage() {
        ModelAndView mv = new ModelAndView("mainAdmin");
        mv.addObject("mainPage","admin/studentAdd.jsp");
        return mv;
    }

    @PostMapping("/add")
    public ModelAndView addStudent(Student student) {
        ModelAndView mv = new ModelAndView("mainAdmin");
        Student studentBySno = studentService.getStudentBySno(student.getSno());
        if (studentBySno != null) {
            mv.addObject("mainPage","admin/studentAdd.jsp");
            mv.addObject("msg","学生"+student.getSno()+"已存在,请勿重复创建");
            return mv;
        }
        studentService.saveStudent(student);
        mv.addObject("mainPage","admin/studentAdd.jsp");
        mv.addObject("msg","学生添加成功");
        return mv;
    }

    @GetMapping("/del/{id}")
    public ModelAndView delStudent(@PathVariable int id) {
        studentService.deleteStudentById(id);
        return studentList(null,null);
    }

    @GetMapping("/edit/{id}")
    public ModelAndView editStudentPage(@PathVariable int id) {
        ModelAndView mv = new ModelAndView("mainAdmin");
        Student stu = studentService.getStudentById(id);
        mv.addObject("stu",stu);
        mv.addObject("mainPage","admin/studentEdit.jsp");
        return mv;
    }

    @PostMapping("/edit/{id}")
    public ModelAndView editStudent(Student student,@PathVariable int id) {
        ModelAndView mv = new ModelAndView("mainAdmin");
        student.setId(id);
        int res = studentService.updateStudent(student);
        if (res > 0) {
            mv.addObject("msg","学生信息更新成功");
        } else {
            mv.addObject("msg","学生信息更新失败");
        }
        Student stu = studentService.getStudentById(id);
        mv.addObject("stu",stu);
        mv.addObject("mainPage","admin/studentEdit.jsp");
        return mv;
    }
}
